package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    @Override
    public void createBed(BedDto bedDto) {
//        Bed bed = new Bed();
//        BeanUtil.copyProperties(bedDto, bed);

//        Bed bed = BeanUtil.copyProperties(bedDto, Bed.class);

        Bed bedDb = bedMapper.getBedByBedNumber(bedDto.getBedNumber());
        if (bedDb != null) {
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPERT_BED_NUM);
        }
        Bed bed = BeanUtil.toBean(bedDto, Bed.class);

        bed.setBedStatus(0);
        bed.setCreateTime(LocalDateTime.now());
        bedMapper.insertBed(bed);
    }

    @Override
    public void updateBed(BedDto bedDto) {
        //判断床位是否被使用
        BedVo bedVo = bedMapper.getBedById(bedDto.getId());
        if (bedVo.getBedStatus() == 1) {
            throw new BaseException(BasicEnum.BED_EDIT_FAIL_INUSE);
        }

        // 判断床位号是否重复
        Long count = bedMapper.countDiffBedNumber(bedDto.getBedNumber(), bedDto.getId());
        if (count > 0) {
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPERT_BED_NUM);
        }
        Bed bed = new Bed();
        BeanUtil.copyProperties(bedDto, bed);
        bed.setCreateTime(LocalDateTime.now());
        bedMapper.updateBed(bed);
    }

    @Override
    public BedVo getBedById(Long id) {
        return BeanUtil.toBean(bedMapper.getBedById(id), BedVo.class);
    }

    @Override
    public void deleteBed(Long id) {
        bedMapper.deleteBed(id);
    }

}

